#!/usr/bin/python
#
# Copyright (C) 2008 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" This sample demonstrates how to search meta resources based on meta elements. """

import time
import rawsc
import rawsc.service
from rawsc import rass
import rawsc.rass.service
from rawsc.rass import Tag, Meta
try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree

# user credentials for authentication to RASS
USER = "XXX"
PWD = "XXX"
SERVER = "rass.cdn0XXX.rambla.be"

# path to a local file that may be uploaded
LOCAL_FILE = "/path/to/local/file.mp4"

try:
    # Create a Rass instance, passing it your login credentials and the base service uri
    client = rawsc.rass.service.RassService(username=USER, password=PWD, server=SERVER)
    
    # Upload a file 'da_funk.mp4' to your dir and attach some metadata to it
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "da_funk.mp4", local_path = LOCAL_FILE)
    meta_entry = client.createMeta(path = item_entry.path,  metas = [Meta(vocab = "dc", meta_name = "creator", text="Rambla"), Meta(vocab = "dc", meta_name = "description", text="Behind the scenes at Ramblaworld"), Meta(vocab = "dc", meta_name = "date", text="2010-12-31"),])
    
    # Upload a file 'stream.mp4' to your dir and attach some metadata to it
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "stream.mp4", local_path = LOCAL_FILE)
    meta_entry = client.createMeta(path = item_entry.path,  metas = [Meta(vocab = "dc", meta_name = "creator", text="Rambla"), Meta(vocab = "dc", meta_name = "description", text="Guide to streaming with Wowza Media Server 02."), Meta(vocab = "dc", meta_name = "title", text="Harder, Better, Faster, Stronger"), Meta(vocab = "dc", meta_name = "date", text="2009-07-09"),])

    # Upload a file 'world.mp4' to your dir and attach some metadata to it
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "world.mp4", local_path = LOCAL_FILE)
    meta_entry = client.createMeta(path = item_entry.path,  metas = [Meta(vocab = "dc", meta_name = "creator", text="Verne Travels"), Meta(vocab = "dc", meta_name = "title", text="Around the World in Eighty Days"), Meta(vocab = "dc", meta_name = "date", text="2008-11-04"),])

    # Upload a file 'clip.mp4' to your dir and attach some metadata to it
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "clip.mp4", local_path = LOCAL_FILE)
    meta_entry = client.createMeta(path = item_entry.path,  metas = [Meta(vocab = "dc", meta_name = "creator", text="Daft Punk"), Meta(vocab = "dc", meta_name = "title", text="Tron: Legacy"), Meta(vocab = "dc", meta_name = "description", text="Music video from the movie TRON legacy."), Meta(vocab = "dc", meta_name = "date", text="2010-12-06"),])
    
    # Upload two test files, without any metadata
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "test1.mp4", local_path = LOCAL_FILE)
    item_entry = client.postItem(dirpath = "/tutorial11/", filename = "test2.mp4", local_path = LOCAL_FILE)

    # 'meta' searches
    print "\nSearch for all files with a 'dc:title' element :"
    qry = rawsc.Query()
    qry["meta"] = "dc:title"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    print "\nSearch for all files that have a 'dc:title' OR 'dc:description' element :"
    qry = rawsc.Query()
    qry["meta"] = "dc:title,dc:description"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    print "\nSearch for all files that have 'dc:creator' set to 'Daft Punk' :"
    qry = rawsc.Query()
    qry["meta"] = "dc:creator:Daft Punk"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    print "\nSearch for all files that have 'dc:creator' set to 'Rambla' but don't have a title element :"
    qry = rawsc.Query()
    qry["meta"] = "dc:creator:rambla,-dc:title"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # 'qmeta' or 'iqmeta' searches on content

    # qmeta is case sensitive
    print "\nCase-sensitive search for all files with meta elements that contain the string 'World' :"
    qry = rawsc.Query()
    qry["qmeta"] = "World"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # iqmeta is case insensitive
    print "\nCase-insensitive search for all files with meta elements that contain the string 'world' :"
    qry = rawsc.Query()
    qry["iqmeta"] = "world"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # search operators can also be used with (i)qmeta
    print "\nCase-insensitive search for all files with meta elements that contain the strings 'world' OR 'rambla' :"
    qry = rawsc.Query()
    qry["iqmeta"] = "world,rambla"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # search operators can also be used with (i)qmeta
    print "\nCase-insensitive search for all files with meta elements that contain the strings '2010' AND 'daft' :"
    qry = rawsc.Query()
    qry["iqmeta"] = "+2010,+daft"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # combined searches are NOT ALLOWED => if set, the meta argument will prevail
    print "\nSearch for all files with 'dc:creator'='Rambla' (the iqmeta argument will be ignored) :"
    qry = rawsc.Query()
    qry["meta"] = "dc:creator:Rambla"
    qry["iqmeta"] = "2010"
    qry["kind"] = "file"
    feed = client.getMetaFeedFromPath(path = "/tutorial11/", query = qry)
    for e in feed.entry:
        print "Meta Entry URI: " + str(e.id.text)

    # # delete the dir recursively (= all files + metadata)
    # client.deleteDirRecursive(path = "/tutorial11/")

except rawsc.service.Error, e:
    print "Error Response from server, contents = %s.\n" % str(e)
    error_dict = e[0] # error dict inside the first tuple elem
    print "status code : " + str(error_dict["status"]) + "\n"
    if error_dict.has_key("body"):
        print "error body : " + error_dict["body"] + "\n"
except rawsc.RawscException, e:
    print "RawscException caught, reason = %s.\n" % str(e)
except StandardError, e:
    print "StandardError caught, reason = %s.\n" % str(e)
except:
    print "unhandled exception caught\n"
